package util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.SecureRandom;
import java.util.Random;

/**
 * @author jmy
 */
public class PushMsgCodeUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(PushMsgCodeUtil.class);
    /**
     * 短信验证码长度
     */
    private static final int MSG_CODE_LENGTH = 4;

    private static Random rand;

    static {
        try {
            rand  = new SecureRandom();
        } catch (Exception e) {
            LOGGER.info("Exception:{}", e.getMessage());
        }
    }


    /**
     * 随机生成短信验证码
     * @return
     */
    public static String generatorRandomCode() { //length表示生成字符串的长度
        String base = "123456789";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < MSG_CODE_LENGTH; i++) {
            int number = rand.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 根据手机号和分钟数生成可计算的随机短信验证码
     * 计算策略：
     * 根据相同种子，相同随机函数，生成的随机数相同这一个特征；
     * 通过验证时候向前递推分钟数
     * 在极端情况下，redis挂掉的情况
     * @param phone
     * @param minute
     * @return
     */
    public static String generatorRandomCodeWithTime(String phone, long minute){
        long phoneNum = Long.parseLong(phone);
        long seed = minute + phoneNum;
        Random random = new Random(seed);
        double data = random.nextDouble();
        int result = (int)(data*10000);

        //不足四位，数字前面补0
        int formatLength = 4;
        String code = String.format("%0" + formatLength + "d", result);
        char firstChar = code.charAt(0);
        if(firstChar == '0'){
            StringBuilder stringBuilder = new StringBuilder(code);
            //第一位是0的情况下更改为5
            stringBuilder.setCharAt(0, '5');
            code = stringBuilder.toString();
        }

        return code;
    }
}
